package de.dopichaj.labrador.inex;


import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

import de.dopichaj.labrador.inex.assess.Assessable;
import de.dopichaj.labrador.inex.assess.MinimalAssessable;


public final class Assessment {

    private static final Assessable nullExhSpec = new MinimalAssessable(0, 0);
    
    /**
     * A map from file ID to maps from XPath to assessment.
     */
    private final Map<String, Map<String, Assessable>> assessments =
        new HashMap<String, Map<String, Assessable>>();

    public Assessable getAssessable(final String file, final String xPath) {
        if (assessments.containsKey(file)) {
            final Map<String, Assessable> pathMap = assessments.get(file);
            if (pathMap.containsKey(xPath)) {
                return pathMap.get(xPath);
            } else {
                return nullExhSpec;
            }
        } else {
            return nullExhSpec;
        }
    }
    
    public double getExhaustivity(final String file, final String xPath) {
        return getAssessable(file, xPath).getExhaustivity();
    }

    public double getSpecificity(String file, String xPath) {
        return getAssessable(file, xPath).getSpecificity();
    }

    public void addAssessment(final String file, final String xPath,
        final double exh, final double spec) {
        
        final Map<String, Assessable> pathMap;
        
        if (assessments.containsKey(file)) {
            pathMap = assessments.get(file);
        } else {
            pathMap = new HashMap<String, Assessable>();
            assessments.put(file, pathMap);
        }
        
        assert !pathMap.containsKey(xPath);
        pathMap.put(xPath, new MinimalAssessable(exh, spec));
    }

    private static abstract class RecallBaseHandler extends DefaultHandler {
        
        private String file;
        private int topicID;

        @Override
        public void startElement(String uri, String localName,
            String qName, Attributes attributes) throws SAXException {
            
            if (qName.equals("topic")) {
                topicID = Integer.valueOf(attributes.getValue("topic-id"));
            } else if (qName.equals("file")) {
                file = attributes.getValue("name");
            } else if (qName.equals("element")) {
                add(topicID, file, attributes.getValue("xpath"),
                    Double.valueOf(attributes.getValue("e")),
                    Double.valueOf(attributes.getValue("s")));
            }
        }

        protected abstract void add(int topicID, String file,
            String xPath, double e, double s);
    }
    
    private final class SingleTopicRecallBaseHandler extends RecallBaseHandler {

        private final int wantedTopicID;
        private boolean foundTopic = false;
        
        public SingleTopicRecallBaseHandler(final int wantedTopicID) {
            this.wantedTopicID = wantedTopicID;
        }
        
        @Override
        protected void add(int topicID, String file, String xPath, double e, double s) {
            if (topicID == wantedTopicID) {
                addAssessment(file, xPath, e, s);
                foundTopic = true;
            }
        }

        public boolean foundTopic() {
            return foundTopic;
        }
    }
    
    private static final class AllTopicsRecallBaseHandler extends RecallBaseHandler {

        private final Map<Integer, Assessment> assessments = new HashMap<Integer, Assessment>();
        
        @Override
        protected void add(int topicID, String file, String xPath, double e, double s) {
            if (!assessments.containsKey(topicID)) {
                assessments.put(topicID, new Assessment());
            }
            assessments.get(topicID).addAssessment(file, xPath, e, s);
        }
    }
    
    /**
     * Read all the assessments in the full recall base.
     * @return a map from topic ID to assessment
     */
    public static Map<Integer, Assessment> readAssessments(final Reader reader)
        throws SAXException, IOException {
        
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        final AllTopicsRecallBaseHandler handler = new AllTopicsRecallBaseHandler();
        xmlReader.setContentHandler(handler);
        xmlReader.parse(new InputSource(reader));
        
        return handler.assessments;
    }
    
    /**
     * Read the topic with the given ID from the XML document.
     * Other topics are ignored.
     * Horrible things will happen if the document is not a recall base.
     * @param reader
     * @param topicID
     * @throws SAXException
     * @throws IOException
     */
    public void readTopic(final Reader reader, final int topicID)
        throws SAXException, IOException {
        
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        final SingleTopicRecallBaseHandler handler = new SingleTopicRecallBaseHandler(topicID);
        xmlReader.setContentHandler(handler);
        xmlReader.parse(new InputSource(reader));
        if (!handler.foundTopic()) {
            throw new SAXException("Topic " + topicID + " not found");
        }
    }

    public List<? extends Assessable> getAssessableList() {
        
        final List<Assessable> result = new ArrayList<Assessable>();
        for (final String file : assessments.keySet()) {
            
            for (final String xPath : assessments.get(file).keySet()) {
                final Assessable assessable = assessments.get(file).get(xPath);
                result.add(assessable);
            }
        }
        return result;
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/